#include "freespacelabel.h"
#include "mainwindow.h"

#include <QTimer>
#include <Windows.h>

FreeSpaceLabel::FreeSpaceLabel(QWidget *parent) :
    blink(false),
    freeMbs(0),
    QLabel(parent)
{
    detectFreeSpace();
}

void FreeSpaceLabel::detectFreeSpace()
{
    quint64 freeBytes, totalBytes;
    QString path = mainWindow->getDbConfig().imagePath;
    QPalette p = palette();
    blink = false;
    if (GetDiskFreeSpaceEx(path.toLatin1().data(), (PULARGE_INTEGER)&freeBytes, (PULARGE_INTEGER)&totalBytes, 0)) {
        freeMbs = freeBytes >> 20;
        setText(tr("Free Space: %1 MB ").arg(QString::number(freeMbs)));
        if (freeMbs < 1000) {
            blink = true;
            p.setColor(QPalette::WindowText, Qt::red);
            blinking();
        } else if (freeMbs < 500) {
            p.setColor(QPalette::WindowText, Qt::yellow);
        } else {
            p.setColor(QPalette::WindowText, Qt::black);
        }
    } else {
        setText(tr("Disk Error "));
        p.setColor(QPalette::WindowText, Qt::red);
    }

    setPalette(p);

    QTimer::singleShot(300000, this, SLOT(detectFreeSpace()));
}

void FreeSpaceLabel::blinking()
{
    static bool b = true;

    if (blink) {
        if (b) {
            setText(tr("Free Space: %1 MB ").arg(QString::number(freeMbs)));
        } else {
            setText(tr("Disk Space Exhausting "));
        }
        b = !b;
        QTimer::singleShot(800, this, SLOT(blinking()));
    }
}
